<template>
  <view class="bottom-nav-h5" :class="navClasses">
    <view class="bottom-nav-h5__container">
      <view 
        v-for="(item, index) in navItems" 
        :key="index"
        class="bottom-nav-h5__item"
        :class="{ 'bottom-nav-h5__item--active': currentIndex === index }"
        @click="handleNavClick(index, item)"
        @touchstart="handleTouchStart"
        @touchend="handleTouchEnd"
      >
        <view class="bottom-nav-h5__icon-wrapper">
          <view class="bottom-nav-h5__icon">
            <!-- 图标图片 -->
            <image 
              v-if="currentIndex === index && item.selectedIcon"
              :src="item.selectedIcon" 
              class="bottom-nav-h5__icon-img"
              mode="aspectFit"
            />
            <image 
              v-else-if="item.icon"
              :src="item.icon" 
              class="bottom-nav-h5__icon-img"
              mode="aspectFit"
            />
            <!-- 文字图标 -->
            <text 
              v-else 
              class="bottom-nav-h5__icon-text"
              :class="{ 'bottom-nav-h5__icon-text--active': currentIndex === index }"
            >
              {{ item.iconText }}
            </text>
          </view>
          
          <!-- 徽章 -->
          <view v-if="item.badge && item.badge !== ''" class="bottom-nav-h5__badge">
            <text class="bottom-nav-h5__badge-text">{{ item.badge }}</text>
          </view>
          
          <!-- 红点 -->
          <view v-if="item.dot" class="bottom-nav-h5__dot"></view>
        </view>
        
        <text 
          class="bottom-nav-h5__text"
          :class="{ 'bottom-nav-h5__text--active': currentIndex === index }"
        >
          {{ item.text }}
        </text>
        
        <!-- 激活指示器 -->
        <view v-if="currentIndex === index" class="bottom-nav-h5__indicator"></view>
      </view>
    </view>
    
    <!-- 安全区域占位 -->
    <view v-if="safeArea" class="bottom-nav-h5__safe-area"></view>
  </view>
</template>

<script>
import routerManager from '../../utils/router.js'

// 为普通 Vue 项目创建 uni 对象模拟
if (typeof uni === 'undefined') {
  // 创建一个全局函数来处理路由更新
  window.updateAppRoute = function(url) {
    // 更新浏览器地址栏
    window.history.pushState(null, '', url)
    
    // 查找并调用 App 实例的路由处理方法
    const appElement = document.getElementById('app')
    if (appElement && appElement.__vue__) {
      const app = appElement.__vue__
      if (app && app.handleRouteChange) {
        console.log('通过 DOM 找到 App 实例，调用 handleRouteChange')
        app.handleRouteChange()
        return true
      }
    }
    
    // 备用方案：触发 popstate 事件
    console.log('使用 popstate 事件作为备用方案')
    window.dispatchEvent(new PopStateEvent('popstate'))
    return false
  }
  
  window.uni = {
    navigateTo(options) {
      console.log('模拟 uni.navigateTo:', options)
      if (options.url) {
        // 构建目标 URL
        const baseUrl = window.location.origin + window.location.pathname.replace(/\/[^\/]*$/, '')
        const targetUrl = baseUrl + options.url + '.html'
        console.log('准备跳转到:', targetUrl)
        
        // 执行实际页面跳转
        try {
          window.location.href = targetUrl
          
          setTimeout(() => {
            if (options.success) {
              options.success({ errMsg: 'navigateTo:ok' })
            }
          }, 100)
        } catch (error) {
          console.error('页面跳转失败:', error)
          if (options.fail) {
            options.fail({ errMsg: 'navigateTo:fail' })
          }
        }
      }
    },
    reLaunch(options) {
      console.log('模拟 uni.reLaunch:', options)
      if (options.url) {
        const newUrl = window.location.origin + options.url
        console.log('重新启动到:', newUrl)
        
        window.updateAppRoute(options.url)
        
        setTimeout(() => {
          if (options.success) {
            options.success({ errMsg: 'reLaunch:ok' })
          }
        }, 100)
      }
    },
    showToast(options) {
      console.log('模拟 uni.showToast:', options)
      alert(options.title || '提示')
    },
    showLoading(options) {
      console.log('模拟 uni.showLoading:', options)
    },
    hideLoading() {
      console.log('模拟 uni.hideLoading')
    },
    showModal(options) {
      console.log('模拟 uni.showModal:', options)
      const result = confirm(options.content || '确认操作？')
      if (options.success) {
        options.success({
          confirm: result,
          cancel: !result
        })
      }
    },
    getSystemInfoSync() {
      console.log('模拟 uni.getSystemInfoSync')
      return {
        platform: 'h5',
        system: 'Windows 10',
        model: 'PC',
        version: '1.0.0',
        pixelRatio: window.devicePixelRatio || 1,
        screenWidth: window.screen.width,
        screenHeight: window.screen.height,
        windowWidth: window.innerWidth,
        windowHeight: window.innerHeight,
        statusBarHeight: 0,
        safeArea: {
          left: 0,
          right: window.innerWidth,
          top: 0,
          bottom: window.innerHeight,
          width: window.innerWidth,
          height: window.innerHeight
        },
        safeAreaInsets: {
          top: 0,
          right: 0,
          bottom: 0,
          left: 0
        }
      }
    },
    switchTab(options) {
      console.log('模拟 uni.switchTab:', options)
      if (options.url) {
        // switchTab 通常用于切换 tabBar 页面，这里直接调用更新路由
        window.updateAppRoute(options.url)
        
        setTimeout(() => {
          if (options.success) {
            options.success({ errMsg: 'switchTab:ok' })
          }
        }, 100)
      }
    }
  }
}

export default {
  name: 'BottomNavH5',
  props: {
    // 导航项数据
    items: {
      type: Array,
      default: () => []
    },
    // 当前激活的索引
    current: {
      type: Number,
      default: 0
    },
    // 是否固定定位
    fixed: {
      type: Boolean,
      default: true
    },
    // 是否显示安全区域
    safeArea: {
      type: Boolean,
      default: true
    },
    // 主题色
    theme: {
      type: String,
      default: 'blue'
    },
    // 是否显示激活指示器
    showIndicator: {
      type: Boolean,
      default: true
    },
    // 是否启用点击动画
    enableAnimation: {
      type: Boolean,
      default: true
    }
  },
  data() {
    return {
      currentIndex: this.current,
      touchStartTime: 0
    }
  },
  computed: {
    navItems() {
      return this.items.length > 0 ? this.items : this.defaultItems
    },
    defaultItems() {
      return [
        {
          text: '首页',
          iconText: '🏠',
          pagePath: '/pages/index/index',
          selectedIcon: '',
          badge: '',
          dot: false
        },
        {
          text: '便民服务',
          iconText: '🛠️',
          pagePath: '/pages/tools/index',
          selectedIcon: '',
          badge: '',
          dot: false
        },
        {
          text: '我的',
          iconText: '👤',
          pagePath: '/pages/personal-center/index',
          selectedIcon: '',
          badge: '',
          dot: false
        }
      ]
    },
    navClasses() {
      return [
        `bottom-nav-h5--theme-${this.theme}`,
        {
          'bottom-nav-h5--fixed': this.fixed,
          'bottom-nav-h5--with-indicator': this.showIndicator
        }
      ]
    }
  },
  watch: {
    current(newVal) {
      this.currentIndex = newVal
    }
  },
  methods: {
    handleNavClick(index, item) {
      console.log('底部导航点击:', index, item)
      
      // 更新当前索引
      this.currentIndex = index
      
      // 触发 change 事件，让父组件决定是否需要跳转
      this.$emit('change', {
        index,
        item
      })
      
      // 移除自动跳转逻辑，完全由父组件控制
    },
    
    navigateToPage(path) {
      // 使用统一的路由管理器
      routerManager.navigateTo(path, {
        success: (res) => {
          console.log('底部导航跳转成功:', path)
        },
        fail: (err) => {
          // 如果普通跳转失败，尝试用reLaunch
          console.warn('navigateTo失败，尝试reLaunch:', err)
          routerManager.reLaunch(path, {
            success: (res) => {
              console.log('底部导航reLaunch成功:', path)
            },
            fail: (err) => {
              console.error('底部导航跳转完全失败:', err)
            }
          })
        }
      })
    },
    
    handleTouchStart() {
      this.touchStartTime = Date.now()
    },
    
    handleTouchEnd() {
      const touchDuration = Date.now() - this.touchStartTime
      if (touchDuration < 200) {
        // 短按，触发点击效果
        this.$emit('tap')
      }
    }
  }
}
</script>

<style lang="scss" scoped>
// 基础样式
.bottom-nav-h5 {
  position: relative;
  background: #ffffff;
  border-top: 1px solid #f0f0f0;
  box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.08);
  z-index: 1000;
  transition: all 0.3s ease;
  
  &--fixed {
    position: fixed;
    bottom: 0;
    left: 0;
    right: 0;
  }
  
  &__container {
    display: flex;
    align-items: center;
    justify-content: space-around;
    padding: 8px 0 4px;
    min-height: 60px;
    position: relative;
  }
  
  &__item {
    position: relative;
    display: flex;
    flex-direction: column;
    align-items: center;
    justify-content: center;
    flex: 1;
    padding: 6px 8px;
    cursor: pointer;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    border-radius: 12px;
    margin: 0 2px;
    user-select: none;
    -webkit-tap-highlight-color: transparent;
    
    &:hover {
      background: rgba(10, 36, 99, 0.05);
      transform: translateY(-2px);
    }
    
    &:active {
      transform: translateY(0) scale(0.95);
    }
    
    &--active {
      .bottom-nav-h5__icon-text {
        color: #0A2463;
        transform: scale(1.1);
      }
      
      .bottom-nav-h5__text {
        color: #0A2463;
        font-weight: 600;
      }
    }
  }
  
  &__icon-wrapper {
    position: relative;
    margin-bottom: 2px;
  }
  
  &__icon {
    position: relative;
    display: flex;
    align-items: center;
    justify-content: center;
    width: 28px;
    height: 28px;
    
    &-img {
      width: 24px;
      height: 24px;
      transition: all 0.3s ease;
    }
    
    &-text {
      font-size: 20px;
      color: #6b7280;
      transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
      line-height: 1;
      
      &--active {
        color: #0A2463;
        transform: scale(1.1);
      }
    }
  }
  
  &__text {
    font-size: 10px;
    color: #6b7280;
    text-align: center;
    line-height: 1.2;
    transition: all 0.3s cubic-bezier(0.4, 0, 0.2, 1);
    white-space: nowrap;
    font-weight: 500;
    
    &--active {
      color: #0A2463;
      font-weight: 600;
    }
  }
  
  &__badge {
    position: absolute;
    top: -4px;
    right: -4px;
    background: linear-gradient(135deg, #ff4757, #ff3742);
    border-radius: 10px;
    min-width: 18px;
    height: 18px;
    display: flex;
    align-items: center;
    justify-content: center;
    padding: 0 4px;
    box-shadow: 0 2px 4px rgba(255, 71, 87, 0.3);
    animation: badgePulse 2s infinite;
    
    &-text {
      color: #ffffff;
      font-size: 10px;
      font-weight: 600;
      line-height: 1;
    }
  }
  
  &__dot {
    position: absolute;
    top: 2px;
    right: 2px;
    width: 6px;
    height: 6px;
    background: #ff4757;
    border-radius: 50%;
    animation: dotPulse 1.5s infinite;
  }
  
  &__indicator {
    position: absolute;
    bottom: -2px;
    left: 50%;
    transform: translateX(-50%);
    width: 20px;
    height: 3px;
    background: #0A2463;
    border-radius: 2px;
    animation: indicatorSlide 0.3s ease-out;
  }
  
  &__safe-area {
    height: env(safe-area-inset-bottom);
    background: #ffffff;
  }
}

// 主题色变体
.bottom-nav-h5 {
  &--theme-orange {
    .bottom-nav-h5__item--active {
      .bottom-nav-h5__icon-text,
      .bottom-nav-h5__text {
        color: #FF6B35;
      }
    }
    
    .bottom-nav-h5__indicator {
      background: #FF6B35;
    }
  }
  
  &--theme-green {
    .bottom-nav-h5__item--active {
      .bottom-nav-h5__icon-text,
      .bottom-nav-h5__text {
        color: #00C851;
      }
    }
    
    .bottom-nav-h5__indicator {
      background: #00C851;
    }
  }
  
  &--theme-purple {
    .bottom-nav-h5__item--active {
      .bottom-nav-h5__icon-text,
      .bottom-nav-h5__text {
        color: #8B5CF6;
      }
    }
    
    .bottom-nav-h5__indicator {
      background: #8B5CF6;
    }
  }
}

// 动画效果
@keyframes badgePulse {
  0%, 100% {
    transform: scale(1);
  }
  50% {
    transform: scale(1.1);
  }
}

@keyframes dotPulse {
  0%, 100% {
    opacity: 1;
    transform: scale(1);
  }
  50% {
    opacity: 0.7;
    transform: scale(1.2);
  }
}

@keyframes indicatorSlide {
  0% {
    width: 0;
    opacity: 0;
  }
  100% {
    width: 20px;
    opacity: 1;
  }
}

// 响应式设计
@media (max-width: 480px) {
  .bottom-nav-h5 {
    &__container {
      padding: 6px 0 2px;
      min-height: 56px;
    }
    
    &__item {
      padding: 4px 6px;
    }
    
    &__icon {
      width: 24px;
      height: 24px;
      
      &-text {
        font-size: 18px;
      }
      
      &-img {
        width: 20px;
        height: 20px;
      }
    }
    
    &__text {
      font-size: 9px;
    }
    
    &__badge {
      min-width: 16px;
      height: 16px;
      top: -3px;
      right: -3px;
      
      &-text {
        font-size: 9px;
      }
    }
    
    &__dot {
      width: 5px;
      height: 5px;
    }
  }
}

@media (min-width: 768px) {
  .bottom-nav-h5 {
    &__container {
      padding: 10px 0 6px;
      min-height: 64px;
    }
    
    &__icon {
      width: 32px;
      height: 32px;
      
      &-text {
        font-size: 22px;
      }
      
      &-img {
        width: 26px;
        height: 26px;
      }
    }
    
    &__text {
      font-size: 11px;
    }
    
    &__badge {
      min-width: 20px;
      height: 20px;
      
      &-text {
        font-size: 11px;
      }
    }
  }
}

@media (min-width: 1024px) {
  .bottom-nav-h5 {
    &__container {
      max-width: 1200px;
      margin: 0 auto;
    }
  }
}

// 深色模式支持
@media (prefers-color-scheme: dark) {
  .bottom-nav-h5 {
    background: #ffffff;
    border-top-color: #e5e7eb;
    box-shadow: 0 -4px 20px rgba(0, 0, 0, 0.1);
    
    &__item {
      &:hover {
        background: rgba(255, 255, 255, 0.05);
      }
    }
    
    &__text {
      color: #9ca3af;
      
      &--active {
        color: #60a5fa;
      }
    }
    
    &__icon-text {
      color: #9ca3af;
      
      &--active {
        color: #60a5fa;
      }
    }
    
    &__safe-area {
      background: #1a1a1a;
    }
  }
}

// 高对比度模式
@media (prefers-contrast: high) {
  .bottom-nav-h5 {
    border-top-width: 2px;
    border-top-color: #000;
    
    &__item {
      &--active {
        .bottom-nav-h5__text,
        .bottom-nav-h5__icon-text {
          color: #000;
          font-weight: 700;
        }
      }
    }
  }
}

// 减少动画模式
@media (prefers-reduced-motion: reduce) {
  .bottom-nav-h5 {
    &__item,
    &__icon-text,
    &__text {
      transition: none;
    }
    
    &__badge,
    &__dot {
      animation: none;
    }
    
    &__indicator {
      animation: none;
    }
  }
}
</style>
